package com.dance.webflux.handler;

import com.dance.webflux.entity.User;
import com.dance.webflux.service.UserService;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class UserHandler {

    private final UserService userService;

    public UserHandler(UserService userService) {
        this.userService = userService;
    }

    /**
     * 根据ID查询用户信息
     * @param serverRequest 请求体
     * @return 响应体
     */
    public Mono<ServerResponse> getUserById(ServerRequest serverRequest){
        int id = Integer.parseInt(serverRequest.pathVariable("id"));
        Mono<User> userById = userService.getUserById(id);
        return userById.flatMap(user -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyValue(user).switchIfEmpty(ServerResponse.notFound().build()));
    }

    /**
     * 查询所有用户
     * @param serverRequest 请求体
     * @return 响应体
     */
    public Mono<ServerResponse> getUserAll(ServerRequest serverRequest){
        Flux<User> allUser = userService.getAllUser();
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(allUser,User.class);
    }

    /**
     * 保存用户信息
     * @param serverRequest 请求体
     * @return 响应体
     */
    public Mono<ServerResponse> saveUserInfo(ServerRequest serverRequest){
        Mono<User> userMono = serverRequest.bodyToMono(User.class);
        return ServerResponse.ok().build(userService.saveUserInfo(userMono));
    }
}
